import { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Trash2, Plus, Loader2 } from 'lucide-react';
import { todosAPI, type Todo } from '@/lib/apiClient';

/**
 * 待办事项应用
 * 支持添加、完成、删除任务，使用数据库 API
 */
export default function TodoList() {
  const [todos, setTodos] = useState<Todo[]>([]);
  const [inputValue, setInputValue] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [page, setPage] = useState(1);
  const [perPage, setPerPage] = useState(10);
  const [query, setQuery] = useState('');
  const [completedFilter, setCompletedFilter] = useState<'all' | 'true' | 'false'>('all');
  const [sort, setSort] = useState<'-created_at' | 'created_at'>('-created_at');
  const [hasNext, setHasNext] = useState(false);
  const [hasPrev, setHasPrev] = useState(false);
  const [total, setTotal] = useState(0);

  // 从 API 加载数据
  useEffect(() => {
    loadTodos();
  }, [page, perPage, query, completedFilter, sort]);

  const loadTodos = async () => {
    try {
      setLoading(true);
      const response = await todosAPI.getAll({
        page,
        per_page: perPage,
        q: query || undefined,
        completed: completedFilter === 'all' ? undefined : completedFilter === 'true',
        sort,
      });
      setTodos(response.todos);
      const p = (response as any).pagination;
      if (p) {
        setHasNext(!!p.has_next);
        setHasPrev(!!p.has_prev);
        setTotal(p.total ?? response.todos.length);
      } else {
        setHasNext(false);
        setHasPrev(page > 1);
        setTotal(response.todos.length);
      }
      setError('');
    } catch (err) {
      console.error('Failed to load todos:', err);
      setError('加载失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  const addTodo = async () => {
    if (inputValue.trim() === '') return;

    try {
      // 乐观更新：先插入临时项
      const tempId = -Date.now();
      const optimistic: Todo = {
        id: tempId,
        text: inputValue,
        completed: false,
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString(),
      };
      setTodos([optimistic, ...todos]);
      const prevInput = inputValue;
      setInputValue('');

      const response = await todosAPI.create(prevInput);
      setTodos((curr) => curr.map((t) => (t.id === tempId ? response.todo : t)));
      setInputValue('');
      setError('');
    } catch (err) {
      console.error('Failed to add todo:', err);
      // 回滚
      setTodos((curr) => curr.filter((t) => t.id >= 0));
      setError('添加失败，请稍后重试');
    }
  };

  const toggleTodo = async (id: number) => {
    const todo = todos.find((t) => t.id === id);
    if (!todo) return;

    try {
      // 乐观更新
      const prev = todo.completed;
      setTodos((curr) => curr.map((t) => (t.id === id ? { ...t, completed: !prev } : t)));
      const response = await todosAPI.update(id, { completed: !prev });
      setTodos((curr) => curr.map((t) => (t.id === id ? response.todo : t)));
      setError('');
    } catch (err) {
      console.error('Failed to update todo:', err);
      // 回滚
      setTodos((curr) => curr.map((t) => (t.id === id ? { ...t, completed: todo.completed } : t)));
      setError('更新失败，请稍后重试');
    }
  };

  const deleteTodo = async (id: number) => {
    try {
      // 乐观删除
      setTodos((curr) => curr.filter((t) => t.id !== id));
      await todosAPI.delete(id);
      setError('');
    } catch (err) {
      console.error('Failed to delete todo:', err);
      // 回滚
      setTodos((_) => _);
      setError('删除失败，请稍后重试');
    }
  };

  const activeTodos = todos.filter((todo) => !todo.completed);
  const completedTodos = todos.filter((todo) => todo.completed);

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div>
        <h1 className="text-3xl font-bold">待办事项</h1>
        <p className="text-muted-foreground">管理您的日常任务</p>
      </div>

      {/* 错误提示 */}
      {error && (
        <div className="rounded-lg bg-destructive/10 p-3 text-sm text-destructive">
          {error}
        </div>
      )}

      {/* 统计信息 */}
      <div className="grid gap-4 md:grid-cols-3">
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              总任务
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{todos.length}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              待完成
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-yellow-600">
              {activeTodos.length}
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              已完成
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">
              {completedTodos.length}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 添加任务 */}
      <Card>
        <CardHeader>
          <CardTitle>添加新任务</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex gap-2">
            <Input
              placeholder="输入任务内容..."
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
              onKeyPress={(e) => e.key === 'Enter' && addTodo()}
            />
            <Button onClick={addTodo} disabled={loading}>
              <Plus className="mr-2 h-4 w-4" />
              添加
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* 查询与筛选 */}
      <Card>
        <CardHeader>
          <CardTitle>查询与筛选</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid gap-3 md:grid-cols-4">
            <div className="col-span-2 flex items-center gap-2">
              <Input
                placeholder="搜索任务..."
                value={query}
                onChange={(e) => {
                  setPage(1);
                  setQuery(e.target.value);
                }}
              />
            </div>
            <div className="flex items-center gap-2">
              <select
                className="h-10 w-full rounded-md border bg-background px-3 text-sm"
                value={completedFilter}
                onChange={(e) => {
                  setPage(1);
                  setCompletedFilter(e.target.value as 'all' | 'true' | 'false');
                }}
              >
                <option value="all">全部</option>
                <option value="false">未完成</option>
                <option value="true">已完成</option>
              </select>
            </div>
            <div className="flex items-center gap-2">
              <select
                className="h-10 w-full rounded-md border bg-background px-3 text-sm"
                value={sort}
                onChange={(e) => setSort(e.target.value as '-created_at' | 'created_at')}
              >
                <option value="-created_at">最新优先</option>
                <option value="created_at">最旧优先</option>
              </select>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 任务列表 */}
      <Card>
        <CardHeader>
          <CardTitle>任务列表</CardTitle>
        </CardHeader>
        <CardContent>
          {loading && todos.length === 0 ? (
            <div className="flex items-center justify-center py-12">
              <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
            </div>
          ) : todos.length === 0 ? (
            <div className="py-12 text-center text-muted-foreground">
              暂无任务，添加一个开始吧！
            </div>
          ) : (
            <div className="space-y-3">
              {todos.map((todo) => (
                <div
                  key={todo.id}
                  className="flex items-center justify-between rounded-lg border p-4 transition-colors hover:bg-accent"
                >
                  <div className="flex items-center gap-3">
                    <input
                      type="checkbox"
                      checked={todo.completed}
                      onChange={() => toggleTodo(todo.id)}
                      className="h-5 w-5 cursor-pointer rounded border-gray-300"
                    />
                    <span
                      className={`text-sm ${
                        todo.completed
                          ? 'text-muted-foreground line-through'
                          : ''
                      }`}
                    >
                      {todo.text}
                    </span>
                  </div>
                  <div className="flex items-center gap-2">
                    {todo.completed && (
                      <Badge variant="default" className="bg-green-600">
                        已完成
                      </Badge>
                    )}
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={() => deleteTodo(todo.id)}
                    >
                      <Trash2 className="h-4 w-4 text-destructive" />
                    </Button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      {/* 分页 */}
      <div className="flex items-center justify-between">
        <div className="text-sm text-muted-foreground">共 {total} 条</div>
        <div className="flex gap-2">
          <select
            className="h-9 rounded-md border bg-background px-2 text-sm"
            value={perPage}
            onChange={(e) => {
              setPage(1);
              setPerPage(parseInt(e.target.value, 10));
            }}
          >
            <option value={5}>5/页</option>
            <option value={10}>10/页</option>
            <option value={20}>20/页</option>
          </select>
          <Button variant="outline" disabled={!hasPrev || loading} onClick={() => setPage((p) => Math.max(1, p - 1))}>
            上一页
          </Button>
          <Button variant="outline" disabled={!hasNext || loading} onClick={() => setPage((p) => p + 1)}>
            下一页
          </Button>
        </div>
      </div>
    </div>
  );
}

